$(function () {
    'use strict';

    // Initialize the jQuery File Upload widget:
    $('#post-form').fileupload({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: post_upload_url,
        always: function (e, data) {
            //alert('after upload');
        },
        autoUpload: true,
        previewMaxWidth: 120,
        previewMaxHeight: 90,

        acceptFileTypes: /(\.|\/)(gif|jpe?g|png|bmp)$/i,
        maxFileSize: 10240000, // 10 MB
        minFileSize: undefined, // No minimal file size
        maxNumberOfFiles: 20,

    });


    // Load existing files:
    $('#fileupload').addClass('fileupload-processing');
    $.ajax({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: $('#post-form').fileupload('option', 'url'),
        dataType: 'json',
        context: $('#post-form')[0]
    }).always(function () {
        $(this).removeClass('fileupload-processing');
    }).done(function (result) {
        $(this).fileupload('option', 'done')
        .call(this, null, {result: result});
    });

    // set is_cover to cookie
    $('input[name="is_cover"]').live('click', function(){
        $.cookie('post_img_cover', $(this).val());    
    });

    $('.add_to_content').live('click', function(e){
        e.preventDefault();
        tinyMCE.execCommand('mceInsertRawHTML',false, '<img src="' + $(this).attr('url') + '" />');
    });
    
    $("#upload-grid").mCustomScrollbar({
        scrollInertia:300,
        horizontalScroll:false,
        advanced:{
            updateOnBrowserResize:true, /*update scrollbars on browser resize (for layouts based on percentages): boolean*/
            updateOnContentResize:true, /*auto-update scrollbars on content resize (for dynamic content): boolean*/
            autoExpandHorizontalScroll:false, /*auto-expand width for horizontal scrolling: boolean*/
            autoScrollOnFocus:true, /*auto-scroll on focused elements: boolean*/
            normalizeMouseWheelDelta:false /*normalize mouse-wheel delta (-1/1)*/
        },
        scrollButtons:{
            enable:true
        },
        theme:"dark-thick"
    });

});



//http://www.tinymce.com/tryit/classic.php
var tinyMceConfig = {
    mode : "textareas",
    selector: "textarea#Post_content",
    plugins: [
        "advlist autolink autosave link image lists charmap print preview hr anchor",
        "wordcount visualblocks visualchars code fullscreen media nonbreaking",
        "table contextmenu directionality emoticons template textcolor paste textcolor"
    ],

    toolbar1: "bold italic underline strikethrough | link unlink anchor insertfile image media | alignleft aligncenter | blockquote",
    toolbar2: "formatselect | hr nonbreaking charmap emoticons | removeformat visualblocks | code preview | restoredraft",

    menubar: false,
    remove_script_host : true,
    //toolbar_items_size: 'small',
    relative_urls : false,
};


// cat select
var catTypeBefore;
var typeBefore;

$("#Post_cat_id").focus(function(){
    catTypeBefore = $('option:selected', this).attr('type');
    typeBefore = $('#Post_type').val();
})
.change(function() {

    var catTypeChange = $('option:selected', this).attr('type');
    
    $('.block-toggle').fadeOut('fast');   

    switch(catTypeChange){
        case 'SALE':
            $('#Post_type option[value$="RENT"]').remove();
            $('#block-type').fadeIn('fast');
            $('#block-state').fadeIn('fast');
            //                $('#block-area').fadeIn('fast');
            $('#block-price').fadeIn('fast');
            $('#block-address').fadeIn('fast');
            break;
        case 'SERVICE':
            //                $('#block-type').fadeIn('fast');
            //                $('#block-state').fadeIn('fast');
            //                $('#block-area').fadeIn('fast');
            $('#block-price').fadeIn('fast');
            $('#block-address').fadeIn('fast');
            break;
        case 'IMMOVABLE':
//            console.log(catTypeBefore);
//            console.log(catTypeChange);
            if(catTypeBefore != undefined && catTypeBefore != catTypeChange){
                $('#Post_type').html('<option value=""></option>'+
                    '<option value="SALE" '+(typeBefore == 'SALE' ? 'selected="selected"' : '')+'>Bán</option>'+
                    '<option value="FOR_RENT">Cho thuê</option>'+
                    '<option value="BUY" '+(typeBefore == 'BUY' ? 'selected="selected"' : '')+'>Mua</option>'+
                    '<option value="RENT">Thuê</option>');
                
            }
            $('#block-type').fadeIn('fast');
            //                $('#block-state').fadeIn('fast');
            $('#block-area-use, #block-area-floor').fadeIn('fast');
            $('#block-price').fadeIn('fast');
            $('#block-address').fadeIn('fast');
            break;
        case 'ARTICLE':
            //                $('#block-type').fadeIn('fast');
            //                $('#block-state').fadeIn('fast');
            //                $('#block-area').fadeIn('fast');
            //                $('#block-price').fadeIn('fast');
            //                $('#block-address').fadeIn('fast');
            break;
    }   

}).change();


$("#Post_city_id").change(function(){
    var city_id = $(this).val();
    $("#Post_district_id").html('<option value=""></option>');
    $.each(districtDataGroupByCityId[city_id], function(key, value){
        $("#Post_district_id").append('<option value="'+key+'">'+value+'</option>');
    });
    if($("#Post_address").val().length > 0){
        write_address_full();    
    }


    google_map(citiesRefID[city_id].latlng);
    $('#Post_latlng').val(citiesRefID[city_id].latlng);
});

$("#Post_district_id").change(function(){
    if($("#Post_address").val().length > 0){
        write_address_full();    
    }
    var latlng = districtsRefID[$(this).val()].latlng != '' ? districtsRefID[$(this).val()].latlng : citiesRefID[city_id].latlng;
    google_map(latlng);
    $('#Post_latlng').val(latlng);
    $("#Post_address").focus();
});

$("#Post_address").bind('change keyup blur focus', function(){
    write_address_full();
});

$('#post-form').submit(function(){
    $('#Post_content').val(tinyMCE.activeEditor.getContent());
    // remove values of fields not need
    switch($('#Post_cat_id option:selected').attr('type')){
        case 'SALE':
            $('#Post_area_use, Post_area_floor').val('');
            break;
        case 'SERVICE':
            $('#Post_area_use, Post_area_floor, #Post_type, #Post_state').val('');
            break;
        case 'IMMOVABLE':
            $('#Post_state').val('');
            break;
        case 'ARTICLE':
            $('#Post_area_use, Post_area_floor, #Post_type, #Post_state, #Post_price, #Post_address').val('');
            break;
    }
})

function google_map(latlng) {
    var latlng = latlng.split(",");
    var lat = latlng[0];
    var lng = latlng[1];

    var center_position = new google.maps.LatLng(lat, lng);
    var marker_position = new google.maps.LatLng(lat, lng);
    var marker;
    var map;

    var mapOptions = {
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: center_position,

        panControl: false,
        mapTypeControl: false,
        zoomControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL,
            position: google.maps.ControlPosition.TOP_RIGHT
        },
        streetViewControl: false,
        scaleControl: false,
        rotateControl: false,
        overviewMapControl: false
    };

    map = new google.maps.Map(document.getElementById('map'), mapOptions);

    marker = new google.maps.Marker({
        map:map,
        draggable:true,
        animation: google.maps.Animation.DROP,
        position: marker_position,
        icon : new google.maps.MarkerImage('/files/img/red_flag.png',
            new google.maps.Size(69,48),
            new google.maps.Point(0,0),
            new google.maps.Point(35,48)
        ),
        shadow: new google.maps.MarkerImage('/files/img/red_flag_shadow.png',
            new google.maps.Size(97,48),
            new google.maps.Point(0,0),
            new google.maps.Point(35,48)
        )
    }); 
    google.maps.event.addListener(marker, 'click', function(){
        if (marker.getAnimation() != null) {
            marker.setAnimation(null);
        } else {
            marker.setAnimation(google.maps.Animation.BOUNCE);
        }
    });

    google.maps.event.addListener(marker, 'dragend', function(){
        var loc = marker.getPosition();
        var lat = roundNumber(loc.lat(),6);
        var lng = roundNumber(loc.lng(),6);
        $('#Post_latlng').val(lat+','+lng);
    });

    google.maps.event.trigger(map, 'resize');
    map.setZoom(map.getZoom());
    //        map.fitBounds(bounds);
}



function write_address_full(){
    var city =       $("#Post_city_id option:selected").text();
    var district =   $("#Post_district_id option:selected").text();
    var address =   $("#Post_address").val();
    var addressFull = (address != '') ? address +', '+ district + ', '+ city : '';
    $('#address_full').val(addressFull);

}
write_address_full();